import React, {useRef, useState} from 'react';
import {Text, StyleSheet, View, Dimensions, Button} from 'react-native';
import {CameraApi, CameraType, Camera} from 'react-native-camera-kit';

const {width} = Dimensions.get('window');
export const ScanCodeDemo: React.FC = (): JSX.Element => {
  const nativeRef = useRef<CameraApi>(null);
  const [zoomStr, setZoomStr] = useState<number>(0);
  const [errorStr, setErrorStr] = useState<string>('');
  const [codeResult, setCodeResult] = useState<string>('');

  const onError = (e: any) => {
    setErrorStr(e.nativeEvent.errorMessage);
  };

  const onZoom = (e: any) => {
    setZoomStr(e.nativeEvent.zoom);
  };

  const onReadCode = (e: any) => {
    setCodeResult(JSON.stringify(e));
  };

  return (
    <View style={styles.container}>
      {codeResult ? (
        <View style={styles.infoContainer}>
          <Button
            title="重新扫码"
            onPress={() => {
              setCodeResult('');
            }}
          />
          <Text style={styles.text}>zoom:{zoomStr}</Text>
          <Text style={styles.text}>code:{codeResult}</Text>
          <Text style={styles.text}>error:{errorStr}</Text>
        </View>
      ) : (
        <View style={styles.cameraContainer}>
          <Camera
            style={{width: width * 0.5, height: width * 0.5 * 1.33}}
            ref={nativeRef}
            maxZoom={50}
            cameraType={CameraType.Back}
            onError={onError}
            onZoom={onZoom}
            scanBarcode
            onReadCode={onReadCode}
            ratioOverlay="4:3"
            showFrame
          />
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center', // 垂直居中
    alignItems: 'center', // 水平居中
    backgroundColor: '#fff',
  },
  cameraContainer: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  infoContainer: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
    color: '#000',
    marginTop: 10,
  },
});

export default ScanCodeDemo;
